<?php

namespace App\Supports\Payment\Methods\Alipay;

use App\Models\Withdraw;
use Exception;
use Carbon\Carbon;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\Log;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodTransfer;

class TransferWithdraw extends Method implements MethodTransfer
{
	public function validate($object = null, $data = null) {}

	public function info($withdraw = null, $data = null)
	{
		$amount = big_decimal($withdraw->actual_amount)
			->toScale(2, RoundingMode::HALF_UP);

		return [
			'out_biz_no' => 'withdraw_'.$withdraw->number,
			'trans_amount' => (string)$amount,
			'product_code' => 'TRANS_ACCOUNT_NO_PWD',
			'biz_scene' => 'DIRECT_TRANSFER',
			'payee_info' => [
				'identity' => $withdraw->user->alipay_user_id,
				'identity_type' => 'ALIPAY_USER_ID',
			],
		];
	}

	public function transfer($withdraw = null, $data = null)
	{
		/**
		 * @var Withdraw $withdraw
		 */

		$this->validate($withdraw);

		try {

			$info = $this->info($withdraw);

			$result = $this->channel->transfer($info);

			if ($result['status'] == 'SUCCESS') {
				/*$fee = $withdraw->user->preFreeWithdrawQuotaAmount($withdraw->target_amount);
				$withdraw->user()->update(['pre_free_withdraw_quota' => $fee]);*/
				$withdraw->update(['paid_at' => Carbon::now(), 'status' => 'paid']);
			} else {
				$withdraw->update(['paid_at' => Carbon::now(), 'status' => 'failed']);
			}
		} catch (Exception $exception) {
            $failedReason = $exception->getCode().$exception->getMessage();
			$withdraw->update(['remark' => "异常: {$failedReason}", 'status' => 'failed']);
		}
	}
}
